<template>
  <div id="map">
    <!-- <el-dropdown trigger="click"  :visible-change="testChange">
      <el-button type="primary">
        更多菜单
        <i class="el-icon-arrow-down el-icon--right"></i>
      </el-button>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item>黄金糕</el-dropdown-item>
        <el-dropdown-item>狮子头</el-dropdown-item>
        <el-dropdown-item>螺蛳粉</el-dropdown-item>
        <el-dropdown-item>双皮奶</el-dropdown-item>
        <el-dropdown-item>蚵仔煎</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>-->
    <div class="person" id="svgBox">
      <div class="nyimg">
        <img src="../../public/image/ny.png" alt width="100%" height="100%" />
      </div>
      <div class="svgWrap">
        <svg
          class="svg"
          ref="svg"
          xmlns="http://www.w3.org/2000/svg"
          width="1195"
          height="821"
          viewBox="0 0 1195 821"
        >
          <!-- <foreignObject width="32" height="32" >
            <div class="test" style="width:32px;height:32px" >
              <img src="../../public/image/3.png" alt="">
            </div>
          </foreignObject>-->
          <!-- </div> -->
          <!-- <text class="imgText" x="25" y="25" font-size="16" style="fill:rgb(255,255,255);" z-index="2"><img src="../../public/image/3.png" alt=""></text> -->

          <!-- <path class="testPath" :d="Drawpath" stroke="#f50" fill="none" style="stroke-width:4px" /> -->
        </svg>
      </div>
    </div>
  </div>
</template>

<script>
import $ from "jquery";
import axios from "axios";
import { baseEnv } from "@/request";
let baseUrl;
let moveTimer = null;
export default {
  data() {
    return {
      a: false,
      src: "",
      isStop: false,
      Drawpath: "M10 ,10"
    };
  },
  mounted() {
    if (baseEnv == "development") {
      baseUrl = "/b";
    } else {
      baseUrl = "https://overall.qcdoc.cn/";
    }
    // 电子围栏
    let polygonArr = [];
    this.axios
      .get(`${baseUrl}/location/getFence?id=2`, {
        headers: {
          "Content-Type": "application/json;charset=UTF-8"
        }
      })
      .then(res => {
        let data = (res.data.data && res.data.data.vertex) || [];
        var keyMap = {
          X: "x",
          Y: "y",
          Z: "z"
        };
        data.forEach((el, index) => {
          // 外层
          el.forEach(e => {
            for (var key in e) {
              var newKey = keyMap[key];
              if (newKey) {
                e[newKey] = e[key];
                delete e[key];
              } else {
                delete e[key];
              }
            }
          });
          polygonArr.push(el);
        });
        for (let i = 0; i < polygonArr.length; i++) {
          let point = polygonArr[i];

          let pointsStr = "";
          for (let j = 0; j < polygonArr[i].length; j++) {
            pointsStr += `${polygonArr[i][j].x},${polygonArr[i][j].y}`;
          }

          // this.createPolygonMaker(pointsStr);
        }
      });
    // 监听弹框事件
    this.$nextTick(() => {
      var domMap;
      var domIds = [];
      var id;
      var svg = document.getElementById("svgBox");
      // var imgDiv2=document.getElementsByClassName("imgDiv2")
      svg.addEventListener("click", ev => {
        var target = ev.target;
        var box = target.parentNode;
        if (target.tagName.toLowerCase() == "img") {
          domMap = target.dataset; // data属性
          let index = arr.findIndex(el => {
            return el.id == parseInt(domMap.id);
          });
          domMap.x = arr[index].x;
          domMap.y = arr[index].y;
          domIds.push(domMap.id);
          let con = this.showPop(domMap);

          $(box).prepend(con);
        } else if (target.tagName.toLowerCase() == "div") {
          let i = domIds.findIndex(el => {
            return el == id;
          });
          id = target.parentNode.dataset.id;
          $(`#popbox${id}`).remove();
        }
      });
    });
    //  运动轨迹
    let arr = [
      { x: 86, y: 414, id: 1, name: "钱海", type: 3 },
      // { x: 10, y: 10, id: 2, name: "访客", type: 0 },
      // { x: 671, y: 214, id: 3, name: "陶程", type: 3 }
    ];
    for (let i = 0; i < arr.length; i++) {
      this.createPerson(
        arr[i].x,
        arr[i].y,
        arr[i].type,
        arr[i].name,
        arr[i].id,
        i
      );
      // this.createpathMaker();
    }
    // 单条线
    this.createpathMaker();
    // 定时获取点位信息
    function moveRoute() {
      //坐标点存储器
      var start = performance.now();
      var boxs = document.querySelectorAll(".imgName");
      var paths = document.querySelectorAll("path");
      var count = 0;
      var oldCount = 1;
      var len;
      var rafId = {}; //批量定义
      var point = {}; // 记录上一个值
      var lens = {}; // 记录最新的path长度
      var frameIndex = 0;
      for (var j = 0; j < arr.length; j++) {
        var pointName = "point" + j; //动态定义变量名
        point[lineName] = []; //动态赋值
        lenName = "len" + j;
        lens[lenName] = [];
      }
      // point[`point${i}`]
      var that = this;
      moveTimer = setInterval(() => {
        that.axios
          .get(`${baseUrl}/location/getPosInfo`, {
            headers: {
              "Content-Type": "application/json;charset=UTF-8"
            }
          })
          .then(res => {
            const alldata = res.data.data; //获取所有人点位信息
            for (let k = 0; k < alldata.length; k++) {
              let pointArr = [alldata[k].posX, alldata[k].posY];
              let pathArr = point[`point${k}`];
              // 画线
              that.setPath(pointArr, point[`point${k}`], paths[k]);
              lens[`len${k}`] = paths[k].getTotalLength();
              that.frame(lens[`len${k}`], count, boxs[k]);
              // 人跟随运动
            }
          });
      }, 1000);
    }
    let pathArr = []; //坐标点
    var that = this;
    function setPath(pointArr) {
      pathArr.push([...pointArr]);
      // that.Drawpath += `L${pointArr[0]},${pointArr[1]}`;
      if (pathArr.length > 5) {
        let prePonit = pathArr.shift();
        console.log(that.Drawpath, "测试数据");
        let pathTemp = that.Drawpath.split("L");
        pathTemp.splice(0, 1);
        console.log(pathTemp.length); // 删除之后

        let str = "";
        for (let i = 0; i < pathTemp.length; i++) {
          if (i == 0) {
            // 第一个
            pathTemp[i] = `M${pathTemp[i]}`;
          } else if (i == pathTemp.length - 1) {
            // 最后一个
            let arr = pathTemp[i].split("M");
            pathTemp[i] = `L${arr[0]}M${arr[1]}`;
          } else {
            // 其他点位
            pathTemp[i] = `L${pathTemp[i]}`;
          }
          str += `${pathTemp[i]}`;
        }
        that.Drawpath = str;
        path.setAttribute("d", that.Drawpath);
        that.Drawpath = `${that.Drawpath}L${pointArr[0]},${pointArr[1]} M${pointArr[0]},${pointArr[1]}`;
      } else {
        let pathTemp = that.Drawpath.split("M");
        pathTemp.length > 2 ? pathTemp.splice(pathTemp.length - 1, 2) : null;
        pathTemp.length > 1 ? pathTemp.splice(0, 1) : null;
        pathTemp[0] = `M${pathTemp[0]}`;
        that.Drawpath = pathTemp[0];
        path.setAttribute("d", that.Drawpath);
        that.Drawpath = `${that.Drawpath}L${pointArr[0]},${pointArr[1]} M${pointArr[0]},${pointArr[1]}`;
      }
    }
    // 记录count的旧值
    let ids = [];
    window.addEventListener("resize", refresh(), false);
    function refresh() {
      var docEl = window.document.documentElement;
      var width = docEl.getBoundingClientRect().width;
      // if (width < 1366) {
      //   rem = width / 24;
      // } else if (width > 2560) {
      //   rem = width / 24;
      // } else {
      //   rem = width / 24;
      // }
    }
    refresh();
    var rem2;
    rem2 = 85.3;
    function frame(len) {
      //len, count, rafId[`rafId$[i]`]
      var now = performance.now(); // 获取时间
      var phase = ((now - start) / 6000) % 1;
      var point = path.getPointAtLength(len * phase);
      box.style.transform =
        "translate3d(" + point.x / rem2 + "rem," + point.y / rem2 + "rem,0)"; // IE
      box.style.WebkitTransform =
        "translate3d(" + point.x / rem2 + "rem," + point.y / rem2 + "rem,0)"; // Chrome&Safari
      let testid = requestAnimationFrame(frame);
      if (that.isStop) cancelAnimationFrame(testid);
      // ids.push(rafIds);

      // if (count == 13) {
      //   console.log(rem2);
      //   console.log(point.x / rem2 + "rem,", point.y / rem2 + "rem,0)");
      //   cancelAnimationFrame(testid);
      //   for (let i = 0; i < ids.length; i++) {
      //     cancelAnimationFrame(ids[i]);
      //   }
      // }
    }
    let pathPointArr = [
      [100, 150],
      [200, 100],
      [300, 300],
      [400, 200],
      [500, 350],
      [600, 250],
      [550, 60],
      [689, 132],
      [789, 222],
      [550, 268],
      [650, 172],
      [750, 220],
      [789, 322],
      [800, 420],
      [900, 520]
    ];
    var start = performance.now();
    var box = document.querySelector(".personDiv1");
    // var box = document.querySelector(".imgText");

    var path = document.querySelector("path");

    var count = 0;
    var oldCount = 1;
    var len;
    var rafId = {}; //批量定义
    pathPointArr.forEach((item, i) => {
      setTimeout(() => {
        count++;
        var rafIdName = "rafId" + i; //动态定义变量名
        rafId[rafIdName] = null; //动态赋值
        setPath(item); // 绘制轨迹
        // len = path.getTotalLength(); // 获取最新的path
        // frame(len, count, rafId[`rafId$[i]`]);
        if (i == 12) {
          that.isStop = true;
        }
        len = path.getTotalLength(); // 获取最新的path

        // frame(len);
      }, i * 1000);
    });
    // len = path.getTotalLength(); // 获取最新的path
    // console.log(len, "------------");

    // frame(len);
  },
  methods: {
    testChange(bool) {
      //只有回调参数为false时才触发 ctx.getAreaListDataSearch(vc,1)这个函数;
      console.log(123);
      console.log("回调参数" + bool);
      // if (!callback) {
      //   var ctx = this;
      //   ctx.AREACODE2 = "请选择";
      //   if (vc != "") {
      //     ctx.show2 = true;
      //     // ctx.getAreaListDataSearch(vc, 1);
      //   }
      // }
    },
    /**
     * @pointArr 实时点位
     * @pathArr  path的数组
     * @path path的dom结构
     */
    setPath(pointArr, pathArr, path) {
      pathArr.push([...pointArr]);
      // that.Drawpath += `L${pointArr[0]},${pointArr[1]}`;
      if (pathArr.length > 5) {
        let prePonit = pathArr.shift(); // 切换原点
        let pathTemp = this.Drawpath.split("L");
        pathTemp.splice(0, 1);
        let str = "";
        for (let i = 0; i < pathTemp.length; i++) {
          if (i == 0) {
            pathTemp[i] = `M${pathTemp[i]}`;
          } else if (i == pathTemp.length - 1) {
            let arr = pathTemp[i].split("M");
            pathTemp[i] = `L${arr[0]}L${arr[1]}`;
          } else {
            pathTemp[i] = `L${pathTemp[i]}`;
          }
          str += `${pathTemp[i]}`;
        }
        this.Drawpath = str;
        path.setAttribute("d", this.Drawpath);
        this.Drawpath = `${this.Drawpath}L${pointArr[0]},${pointArr[1]} M${pointArr[0]},${pointArr[1]}`;
      } else {
        let pathTemp = this.Drawpath.split("M");
        pathTemp.length > 2 ? pathTemp.splice(pathTemp.length - 1, 2) : null;
        pathTemp.length > 1 ? pathTemp.splice(0, 1) : null;
        pathTemp[0] = `M${pathTemp[0]}`;
        this.Drawpath = pathTemp[0];
        path.setAttribute("d", this.Drawpath);
        this.Drawpath = `${this.Drawpath}L${pointArr[0]},${pointArr[1]} M${pointArr[0]},${pointArr[1]}`;
      }
    },
    // rafIds,
    frame(len, count, box) {
      var rem2;
      rem2 = 85.3;
      //len, count, rafId[`rafId$[i]`]
      var now = performance.now(); // 获取时间
      var phase = ((now - start) / 6000) % 1;
      var point = path.getPointAtLength(len * phase);
      box.style.transform =
        "translate3d(" + point.x / rem + "rem," + point.y / rem + "rem,0)"; // IE
      box.style.WebkitTransform =
        "translate3d(" + point.x / rem + "rem," + point.y / rem + "rem,0)"; // Chrome&Safari
      rafIds = requestAnimationFrame(frame);
      ids.push(rafIds);
      // if (count == 13) {
      //   console.log(rem2);
      //   console.log(point.x / rem2 + "rem,", point.y / rem2 + "rem,0)");
      //   for (let i = 0; i < ids.length; i++) {
      //     cancelAnimationFrame(ids[i]);
      //   }
      // }
    },
    createPerson(x, y, type, name, id, i) {
      var personDiv = document.createElement("div");
      var imgDiv = document.createElement("div");
      var person = document.createElement("img");
      person.className = "imgName";
      imgDiv.className = "imgDiv" + i;
      personDiv.className = "personDivWrap personDiv" + i;
      if (type == 0) {
        this.src = require("../../public/image/0.png");
      } else {
        this.src = require("../../public/image/3.png");
      }
      person.src = this.src;
      person.setAttribute("data-id", id);
      person.setAttribute("data-name", name);
      person.setAttribute("data-type", type);
      // $(person)
      //   // .addClass("person")
      //   .css({
      //     width: 32,
      //     height: 32,
      //     // position: "relative",
      //     position: "absolute",
      //     top: x - 16,
      //     left: y - 16,
      //     zIndex: 10
      //   })
      //   .appendTo(".person");
      // .appendTo(".imgDiv");
      $(personDiv)
        .css({
          width: 32,
          height: 32,
          top: x - 16,
          left: y - 16,
          position: "absolute"
        })
        .appendTo(`.person`);
      $(imgDiv)
        .css({
          width: 32,
          height: 32,
          position: "relative"
        })
        .appendTo(`.personDiv${i}`);
      $(person)
        .css({
          width: 32,
          height: 32
        })
        .appendTo(`.imgDiv${i}`);
    },
    createPolygonMaker(coords) {
      var polygon = document.createElementNS(
        "http://www.w3.org/2000/svg",
        "polygon"
      );
      polygon.setAttribute("points", coords);
      polygon.setAttribute(
        "style",
        "fill:#f50;strock:#f50;stroke-width:4;  opacity: 0.6;"
      );
      $(polygon).appendTo(".svg");
    },
    createpathMaker() {
      var pathMaker = document.createElementNS(
        "http://www.w3.org/2000/svg",
        "path"
      );
      pathMaker.setAttribute("class", "testPath");
      pathMaker.setAttribute("d", this.Drawpath);
      pathMaker.setAttribute("stroke", "#f50");
      pathMaker.setAttribute(
        "style",
        "fill:none;strock:#f50;stroke-width:4px;"
      );
      $(pathMaker).appendTo(".svg");
    },
    // 判断两点是否相等
    ckSamePt(p1, p2) {
      if (Math.abs(p1.x - p2.x) < 0.0001 && Math.abs(p1.y - p2.y) < 0.0001) {
        //判断两点间距离
        return true;
      }
      return false;
    },
    showPop(data) {
      var types = {
        "1": "摄像头",
        "2": "消防设备",
        "3": "员工",
        "0": "访客"
      };
      let content =
        `<div class="popbox" id="popbox${data.id}" data-id="${data.id}" style="top:32px;left:0px;">` +
        '<div class="title"><span style="margin: 20px;">信息弹框</span></div>' +
        '<div class="m-box">' +
        '<div class="m-text">' +
        "<p>" +
        '<span class="m-span">id</span>' +
        '<span class="m-span">名称</span>' +
        '<span class="m-span">类型</span>' +
        "</p>" +
        "<p>" +
        '<span class="m-span2">' +
        data.id +
        "</span>" +
        '<span class="m-span2 status">' +
        data.name +
        "</span>" +
        '<span class="m-span2 ">' +
        types[data.type] +
        "</span>" +
        "</p>" +
        "</div>" +
        "</div>" +
        '<div class="myPopClose ' +
        "rock-box m-pop" +
        '"></div>' +
        "</div>";
      return content;
    }
  }
};
</script>

<style>
#map {
  width: 100%;
  height: 100%;
  position: relative;
}
#map img {
  width: 100%;
  height: 100%;
}
.person {
  width: 100%;
  height: 100%;
  position: relative;
}
.svgWrap {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
.svg,
.nyimg {
  width: 100%;
  height: 100%;
}
.svg {
  position: relative;
}
.imgText {
  position: absolute;
}
.popbox {
  width: 3rem;
  position: absolute;
  z-index: 100;
  background-color: cadetblue;
}
.title_p {
  border-left: 5px solid #09f;
  font-weight: 700;
  font-size: 0.8vw;
  line-height: 16px;
  padding-left: 10px;
  color: #333;
  margin-bottom: 12px;
}

#toolcheck {
  position: absolute;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
  display: none;
}

#content {
  display: flex;
  justify-content: center;
  height: 100%;
  /* box-shadow: rgba(0, 0, 0, 0.3) 2px 2px 3px; */
  position: relative;
  width: 100%;
  /* overflow: hidden; */
  margin-top: -0.5rem;
  /* background-color: black; */
}

#map-container {
  height: 100%;
  width: 100%;
  /* height: 800px;
  width: 80%; */
  position: relative;
}

.viewmode-group {
  position: absolute;
  right: 12px;
  top: 160px;
  border-radius: 6px;
  border: none;
}

.viewmode-group button {
  display: inline-block;
  width: 38px;
  height: 38px;
  border-radius: 4px;
  border: none;
  background-image: url("../../public/image/wedgets/3D.png");
}

.testPath {
  stroke-dasharray: 5000;
  stroke-dashoffset: 5000;
  animation: dash 1s linear 1;
  animation-fill-mode: forwards;
}

@keyframes dash {
  to {
    stroke-dashoffset: 0;
  }
}
</style>